<template>
  <div id="spread-host">
    <gc-spread-sheets
      hostClass="spreadHost"
      @workbookInitialized="initWorkbook"
    >
    </gc-spread-sheets>
  </div>
</template>

<script>
import { PopupCommon } from "@/libs/popupCommon";
import { SpreadCommon, Utility } from "@/libs/utility";
import * as GC from "@grapecity-software/spread-sheets";
import "@grapecity-software/spread-sheets-vue";
import "@grapecity-software/spread-sheets/styles/gc.spread.sheets.excel2016colorful.css";
let sheet = null;
var self = null;
let sheetCount = 0;
let spreadNS = GC.Spread.Sheets;
let searchIndex = [];
let searchCurIndex = 0;
export default {
  props: {
    /** 数据源：这里不确定字段，只要是数组就可以 */
    dataSource: {
      /** 这里不确定字段，只要是数组就可以 */
      type: Array,
      required: true,
    },
  },
  components: {},
  data() {
    return {};
  },
  methods: {
    search(keyword, isSame) {
      if (!isSame) {
        if (searchIndex.length > 0) {
          let searchStyle = new spreadNS.Style();
          searchStyle.hAlign = GC.Spread.Sheets.HorizontalAlign.left;
          searchStyle.foreColor = "#000000";
          searchIndex.forEach((i) => {
            sheet.setStyle(i, 0, searchStyle, spreadNS.SheetArea.viewport);
          });
        }
        searchIndex = [];
        searchCurIndex = 0;
        var filter = sheet.rowFilter(),
          value = keyword,
          col = 0;

        if (filter) {
          filter.removeFilterItems(col);

          var condition = new GC.Spread.Sheets.ConditionalFormatting.Condition(
            GC.Spread.Sheets.ConditionalFormatting.ConditionType.textCondition,
            {
              compareType:
                GC.Spread.Sheets.ConditionalFormatting.TextCompareType.contains,
              expected: "*" + value + "*",
            }
          );
          filter.addFilterItem(col, condition);
          filter.filter();

          const allFilter = filter._ct;

          let firstRow = 0;
          let index = 0;
          if (allFilter) {
            let leftStyle = new spreadNS.Style();
            leftStyle.hAlign = GC.Spread.Sheets.HorizontalAlign.left;
            leftStyle.foreColor = "#009ddf";
            for (let key in allFilter) {
              if (index == 0) {
                firstRow = parseInt(key);
                searchCurIndex = 0;
              }
              searchIndex.push(parseInt(key));
              index++;
              sheet.setStyle(key, 0, leftStyle, spreadNS.SheetArea.viewport);
            }
          }

          sheet
            .getRange(-1, -1, -1, -1, GC.Spread.Sheets.SheetArea.viewport)
            .setBorder(
              new GC.Spread.Sheets.LineBorder(
                "#e0e0e0",
                GC.Spread.Sheets.LineStyle.thin
              ),
              { all: true },
              1
            );

          sheet.invalidateLayout();
          sheet.repaint();

          sheet.showRow(firstRow, GC.Spread.Sheets.HorizontalPosition.left);
          sheet.setActiveCell(firstRow, 0);
          sheet.resumePaint();
        }
      } else {
        if (searchCurIndex != searchIndex.length - 1) {
          searchCurIndex++;
          sheet.showRow(
            searchIndex[searchCurIndex],
            GC.Spread.Sheets.HorizontalPosition.left
          );
          sheet.setActiveCell(searchIndex[searchCurIndex], 0);
        } else {
          PopupCommon.notify("info", "已经是最后一个了");
        }
      }
    },
    /** 定位到某个单元格 */
    goToPosition(row, col) {
      sheet.showRow(row - 1, GC.Spread.Sheets.HorizontalPosition.left);
      sheet.setActiveCell(row, col);
    },
    setValue(row, col, value) {
      sheet.setValue(row, col, value);
    },
    initWorkbook: (spread) => {
      var str = sessionStorage.getItem("globalData");
      if (str) {
        str = JSON.parse(str);
      }
      var newData = Utility.arrayFlat(str, (t) => t.children);
      sheetCount = newData.length;
      spread.options.tabStripVisible = false; // 把sheet隐藏
      spread.options.allowContextMenu = false;
      spread.options.newTabVisible = false;
      spread.options.allowUserDragDrop = false; // 不允许移动，不会出现移动的鼠标样式
      spread.options.allowUserDragFill = false; //  不允许拉动填满，不会出现十字架的鼠标样式
      spread.options.allowUserResize = true;
      spread.options.scrollbarMaxAlign = true;
      spread.options.scrollbarShowMax = true;

      sheet = spread.getActiveSheet();
      sheet.reset();

      function SelectionFilter(range) {
        spreadNS.Filter.RowFilterBase.call(this, range);
      }
      SelectionFilter.prototype = new spreadNS.Filter.RowFilterBase();
      SelectionFilter.prototype.onFilter = function (args) {
        var sheet = args.sheet,
          range = args.range,
          filterRows = args.filteredRows,
          action = args.action,
          doFilter = action === spreadNS.Filter.FilterActionType.filter;

        if (doFilter) {
          if (range.col < 0) {
            range.col = 0;
            range.colCount = sheet.getColumnCount();
          }
          var activeCellSet;
          for (var i = 0, len = filterRows.length; i < len; i++) {
            var r = filterRows[i];
            for (
              var c = range.col, len1 = range.col + range.colCount;
              c < len1;
              c++
            ) {
              if (!activeCellSet) {
                activeCellSet = true;
                sheet.setSelection(r, c, 1, 1);
              } else {
                sheet.addSelection(r, c, 1, 1);
              }
            }
          }
        } else {
          sheet.setSelection(0, 0, 1, 1);
        }

        spread.focus();
      };

      var actionFilter = new SelectionFilter(
        new spreadNS.Range(0, 0, sheetCount, 1)
      );
      sheet.rowFilter(actionFilter);
      actionFilter.filterButtonVisible(false);

      sheet.suspendPaint();
      sheet.options.isProtected = true;
      sheet.options.protectionOptions = {
        // 允许折叠行
        allowOutlineRows: true,
        // 布尔值，用户是否可以对一片单元格区域进行排序。
        allowSort: true,
        // 布尔值，用户是否可以对一片单元格区域进行筛选。
        allowFilter: true,
        // 布尔值，用户是否可以改变列宽。
        allowResizeColumns: true,
      };
      var initColumn = [
        { name: "FolderName", displayName: "目录名称", size: 300 },
        { name: "EnCode", displayName: "编码", size: 300 },
        { name: "FolderTypeName", displayName: "目录类型", size: 200 },
      ];

      sheet.setDataSource(newData);
      sheet.bindColumns(initColumn);
      // let parentColumnIndex: number[] = []
      for (let r = 0, len = newData.length; r < len; r++) {
        let level = newData[r].level ? newData[r].level : 1;
        // if (level == 1) {
        //     parentColumnIndex.push(r)
        // }
        sheet.getCell(r, 0).textIndent(level);
        // // 可编辑
        // if (datasource[r].hasChildren == false && datasource[r].relatedCount < 1 && formulaData.filter((b: any) => b.itemId == datasource[r].id).length < 1) {
        //     SpreadCommon.setEditColorForCustom(sheet, r, 1)
        // }
      }

      SpreadCommon.initOutlineColumn(sheet, false);
      // 冻结列
      sheet.frozenColumnCount(1);
      //冻结线颜色设置
      sheet.options.frozenlineColor = "#e6e6e6";
      SpreadCommon.setSheetHeight(sheet);
      SpreadCommon.setCommonColor(sheet);
      // 先解除所有绑定，不然会绑定很多次
      sheet.unbindAll();

      /** 单元格点击事件 */
      sheet.bind(GC.Spread.Sheets.Events.CellClick, function (sender, args) {
        if (args.sheetArea === GC.Spread.Sheets.SheetArea.colHeader) {
          return;
        }
        let tempRows = [];
        let tempCols = [];
        let tempData = [];
        var selections = sheet.getSelections();
        if (selections && selections.length > 0) {
          selections.forEach((item) => {
            if (item.row == -1) {
              item.row = 0;
            }
            if (item.col == -1) {
              item.col = 0;
            }
            for (
              let index = item.row;
              index < item.row + item.rowCount;
              index++
            ) {
              if (
                (tempData.length == 0 ||
                  tempData?.filter((t) => t.Id == newData?.[index]?.Id)
                    ?.length < 1) &&
                newData?.[index]?.Id
              ) {
                tempData.push(newData?.[index]);
                tempRows.push(index);
              }
            }
            for (
              let colIndex = item.col;
              colIndex < item.col + item.colCount;
              colIndex++
            ) {
              tempCols.push(colIndex);
            }
          });
        }
        self.$emit("cellClick", {
          tempData,
          tempCols,
          tempRows,
        });
        // props?.onRowSelect && props?.onRowSelect(tempData, tempCols, tempRows);
      });

      sheet.resumePaint();
    },
  },
  mounted() {
    self = this;
  },
};
</script>

<style scoped>
.spreadHost {
  width: 100%;
  height: calc(100vh - 150px);
}
</style>
